from django.contrib.auth.models import Permission, Group
from django.contrib.contenttypes.models import ContentType
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from meiduo_admin.serializers.permissions import PermissionSerializer, ContentTypeSerializer, GroupSerializer, \
    GroupSimpleSerializer
from meiduo_admin.serializers.permissions import AdminUserSerializer
from users.models import User


class PermissionViewSet(ModelViewSet):
    permission_classes = [IsAdminUser]

    lookup_value_regex = '\d+'
    # GET /meiduo_admin/permission/perms/ -->list
    # POST /meiduo_admin/permission/perms/ -->create
    queryset = Permission.objects.all()
    serializer_class = PermissionSerializer

    # def list(self, request):
    #     """获取一组数据的通用代码流程"""
    #     queryset = self.get_queryset()
    #     serializer = self.get_serializer(queryset, many=True)
    #     return Response(serializer.data)

    # def create(self,request):
    #     """新增一条数据的通用代码流程"""
    #     serializer = self.get_serializer(data=request.data)
    #     serializer.is_valid(raise_exception=True)
    #     serializer.save()  # 调用序列化器类中的create方法
    #     return Response(serializer.data, status=201)

    # / meiduo_admin / permission / content_types /
    def content_types(self,request):

        # 1.查询所有数据
        c_types = ContentType.objects.all()
        # 2.
        serializer = ContentTypeSerializer(c_types,many=True)
        return Response(serializer.data)

class GroupViewSet(ModelViewSet):
    permission_classes = [IsAdminUser]

    lookup_value_regex = '\d+'

    queryset = Group.objects.all()
    serializer_class = GroupSerializer

    # GET /meiduo_admin/permission/simple/
    # POST /meiduo_admin/permission/simple/
    def simple(self,request):
        # 1.查
        perms = Permission.objects.all()
        # 2.返回数据
        serializer = PermissionSerializer(perms,many=True)
        return Response(serializer.data)

    # def create(self,request):
    #     """新增一条数据的通用代码流程"""
    #     serializer = self.get_serializer(data=request.data)
    #     serializer.is_valid(raise_exception=True)
    #     serializer.save()  # 调用序列化器类中的create方法
    #     return Response(serializer.data, status=201)


# GET /meiduo_admin/permission/admins/
class AdminViewSet(ModelViewSet):
    permission_classes = [IsAdminUser]
    lookup_value_regex = '\d+'

    queryset = User.objects.filter(is_staff=True)
    serializer_class = AdminUserSerializer

    def simple(self,request):
        # 1.查
        groups = Group.objects.all()
        # 2.返回数据
        serializer = GroupSimpleSerializer(groups,many=True)
        return Response(serializer.data)